/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.arrye.BayImg;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.util.Hashtable;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import org.netbeans.microedition.lcdui.SplashScreen;
import org.netbeans.microedition.lcdui.WaitScreen;
import org.netbeans.microedition.util.SimpleCancellableTask;

/**
 * @author Wilson.ARG
 */
public class Browser extends MIDlet implements CommandListener {

    private boolean midletPaused = false;
    private int pageNumber = 1;
    private int imagesPerPage = 9;
    private String tag = null;
    private String error = null;
    private Hashtable images = null;

//<editor-fold defaultstate="collapsed" desc=" Generated Fields ">//GEN-BEGIN:|fields|0|
private SplashScreen splashScreen;
private Form searchForm;
private TextField tagField;
private ChoiceGroup optionsChoice;
private WaitScreen waitScreen;
private ImageViewer imageViewer;
private ImageList imageList;
private Alert alert;
private Command exitCommand;
private Command searchCommand;
private Command cancelSearch;
private Command viewCommand;
private Command backCommand;
private Command nextCommand;
private Command prevCommand;
private SimpleCancellableTask task;
//</editor-fold>//GEN-END:|fields|0|

    /**
     * The Browser constructor.
     */
    public Browser() {
    }

//<editor-fold defaultstate="collapsed" desc=" Generated Methods ">//GEN-BEGIN:|methods|0|
//</editor-fold>//GEN-END:|methods|0|

//<editor-fold defaultstate="collapsed" desc=" Generated Method: initialize ">//GEN-BEGIN:|0-initialize|0|0-preInitialize
/**
 * Initilizes the application.
 * It is called only once when the MIDlet is started. The method is called before the <code>startMIDlet</code> method.
 */
private void initialize () {//GEN-END:|0-initialize|0|0-preInitialize
        // write pre-initialize user code here
//GEN-LINE:|0-initialize|1|0-postInitialize
        // write post-initialize user code here
}//GEN-BEGIN:|0-initialize|2|
//</editor-fold>//GEN-END:|0-initialize|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Method: startMIDlet ">//GEN-BEGIN:|3-startMIDlet|0|3-preAction
/**
 * Performs an action assigned to the Mobile Device - MIDlet Started point.
 */
public void startMIDlet () {//GEN-END:|3-startMIDlet|0|3-preAction
        // write pre-action user code here
switchDisplayable (null, getSplashScreen ());//GEN-LINE:|3-startMIDlet|1|3-postAction
        // write post-action user code here
}//GEN-BEGIN:|3-startMIDlet|2|
//</editor-fold>//GEN-END:|3-startMIDlet|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Method: resumeMIDlet ">//GEN-BEGIN:|4-resumeMIDlet|0|4-preAction
/**
 * Performs an action assigned to the Mobile Device - MIDlet Resumed point.
 */
public void resumeMIDlet () {//GEN-END:|4-resumeMIDlet|0|4-preAction
        // write pre-action user code here
//GEN-LINE:|4-resumeMIDlet|1|4-postAction
        // write post-action user code here
}//GEN-BEGIN:|4-resumeMIDlet|2|
//</editor-fold>//GEN-END:|4-resumeMIDlet|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Method: switchDisplayable ">//GEN-BEGIN:|5-switchDisplayable|0|5-preSwitch
/**
 * Switches a current displayable in a display. The <code>display</code> instance is taken from <code>getDisplay</code> method. This method is used by all actions in the design for switching displayable.
 * @param alert the Alert which is temporarily set to the display; if <code>null</code>, then <code>nextDisplayable</code> is set immediately
 * @param nextDisplayable the Displayable to be set
 */
public void switchDisplayable (Alert alert, Displayable nextDisplayable) {//GEN-END:|5-switchDisplayable|0|5-preSwitch
        // write pre-switch user code here
Display display = getDisplay ();//GEN-BEGIN:|5-switchDisplayable|1|5-postSwitch
if (alert == null) {
display.setCurrent (nextDisplayable);
} else {
display.setCurrent (alert, nextDisplayable);
}//GEN-END:|5-switchDisplayable|1|5-postSwitch
        // write post-switch user code here
}//GEN-BEGIN:|5-switchDisplayable|2|
//</editor-fold>//GEN-END:|5-switchDisplayable|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Method: commandAction for Displayables ">//GEN-BEGIN:|7-commandAction|0|7-preCommandAction
/**
 * Called by a system to indicated that a command has been invoked on a particular displayable.
 * @param command the Command that was invoked
 * @param displayable the Displayable where the command was invoked
 */
public void commandAction (Command command, Displayable displayable) {//GEN-END:|7-commandAction|0|7-preCommandAction
        // write pre-action user code here
if (displayable == imageList) {//GEN-BEGIN:|7-commandAction|1|70-preAction
if (command == backCommand) {//GEN-END:|7-commandAction|1|70-preAction
 // write pre-action user code here
switchDisplayable (null, getSearchForm ());//GEN-LINE:|7-commandAction|2|70-postAction
 // write post-action user code here
} else if (command == exitCommand) {//GEN-LINE:|7-commandAction|3|72-preAction
 // write pre-action user code here
exitMIDlet ();//GEN-LINE:|7-commandAction|4|72-postAction
 // write post-action user code here
} else if (command == nextCommand) {//GEN-LINE:|7-commandAction|5|89-preAction
 // write pre-action user code here
goNextPage ();//GEN-LINE:|7-commandAction|6|89-postAction
 // write post-action user code here
} else if (command == prevCommand) {//GEN-LINE:|7-commandAction|7|92-preAction
 // write pre-action user code here
goPrevPage ();//GEN-LINE:|7-commandAction|8|92-postAction
 // write post-action user code here
} else if (command == viewCommand) {//GEN-LINE:|7-commandAction|9|74-preAction
 // write pre-action user code here
viewImage ();//GEN-LINE:|7-commandAction|10|74-postAction
 // write post-action user code here
}//GEN-BEGIN:|7-commandAction|11|79-preAction
} else if (displayable == imageViewer) {
if (command == backCommand) {//GEN-END:|7-commandAction|11|79-preAction
 // write pre-action user code here
switchDisplayable (null, getImageList ());//GEN-LINE:|7-commandAction|12|79-postAction
 // write post-action user code here
}//GEN-BEGIN:|7-commandAction|13|19-preAction
} else if (displayable == searchForm) {
if (command == exitCommand) {//GEN-END:|7-commandAction|13|19-preAction
                // write pre-action user code here
exitMIDlet ();//GEN-LINE:|7-commandAction|14|19-postAction
                // write post-action user code here
} else if (command == searchCommand) {//GEN-LINE:|7-commandAction|15|22-preAction
                // write pre-action user code here
    pageNumber = 1;
switchDisplayable (null, getWaitScreen ());//GEN-LINE:|7-commandAction|16|22-postAction
                // write post-action user code here
}//GEN-BEGIN:|7-commandAction|17|15-preAction
} else if (displayable == splashScreen) {
if (command == SplashScreen.DISMISS_COMMAND) {//GEN-END:|7-commandAction|17|15-preAction
                // write pre-action user code here
switchDisplayable (null, getSearchForm ());//GEN-LINE:|7-commandAction|18|15-postAction
                // write post-action user code here
}//GEN-BEGIN:|7-commandAction|19|30-preAction
} else if (displayable == waitScreen) {
if (command == WaitScreen.FAILURE_COMMAND) {//GEN-END:|7-commandAction|19|30-preAction
                // write pre-action user code here
switchDisplayable (getAlert (), getSearchForm ());//GEN-LINE:|7-commandAction|20|30-postAction
                // write post-action user code here
} else if (command == WaitScreen.SUCCESS_COMMAND) {//GEN-LINE:|7-commandAction|21|29-preAction
                // write pre-action user code here
switchDisplayable (null, getImageList ());//GEN-LINE:|7-commandAction|22|29-postAction
                // write post-action user code here
} else if (command == cancelSearch) {//GEN-LINE:|7-commandAction|23|34-preAction
                // write pre-action user code here
switchDisplayable (null, getSearchForm ());//GEN-LINE:|7-commandAction|24|34-postAction
                // write post-action user code here
}//GEN-BEGIN:|7-commandAction|25|7-postCommandAction
}//GEN-END:|7-commandAction|25|7-postCommandAction
        // write post-action user code here
}//GEN-BEGIN:|7-commandAction|26|
//</editor-fold>//GEN-END:|7-commandAction|26|



//<editor-fold defaultstate="collapsed" desc=" Generated Getter: splashScreen ">//GEN-BEGIN:|13-getter|0|13-preInit
/**
 * Returns an initiliazed instance of splashScreen component.
 * @return the initialized component instance
 */
public SplashScreen getSplashScreen () {
if (splashScreen == null) {//GEN-END:|13-getter|0|13-preInit
            // write pre-init user code here
splashScreen = new SplashScreen (getDisplay ());//GEN-BEGIN:|13-getter|1|13-postInit
splashScreen.setTitle ("splashScreen");
splashScreen.setCommandListener (this);
splashScreen.setFullScreenMode (true);
splashScreen.setText ("Arr-Ye! labs presents:\nBayImg browser (beta)");//GEN-END:|13-getter|1|13-postInit
            // write post-init user code here
}//GEN-BEGIN:|13-getter|2|
return splashScreen;
}
//</editor-fold>//GEN-END:|13-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: searchForm ">//GEN-BEGIN:|17-getter|0|17-preInit
/**
 * Returns an initiliazed instance of searchForm component.
 * @return the initialized component instance
 */
public Form getSearchForm () {
if (searchForm == null) {//GEN-END:|17-getter|0|17-preInit
            // write pre-init user code here
searchForm = new Form ("Search Images", new Item[] { getTagField (), getOptionsChoice () });//GEN-BEGIN:|17-getter|1|17-postInit
searchForm.addCommand (getExitCommand ());
searchForm.addCommand (getSearchCommand ());
searchForm.setCommandListener (this);//GEN-END:|17-getter|1|17-postInit
            // write post-init user code here
}//GEN-BEGIN:|17-getter|2|
return searchForm;
}
//</editor-fold>//GEN-END:|17-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: tagField ">//GEN-BEGIN:|23-getter|0|23-preInit
/**
 * Returns an initiliazed instance of tagField component.
 * @return the initialized component instance
 */
public TextField getTagField () {
if (tagField == null) {//GEN-END:|23-getter|0|23-preInit
            // write pre-init user code here
tagField = new TextField ("Tag:", "", 10, TextField.ANY);//GEN-BEGIN:|23-getter|1|23-postInit
tagField.setLayout (ImageItem.LAYOUT_DEFAULT);//GEN-END:|23-getter|1|23-postInit
            // write post-init user code here
}//GEN-BEGIN:|23-getter|2|
return tagField;
}
//</editor-fold>//GEN-END:|23-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: optionsChoice ">//GEN-BEGIN:|24-getter|0|24-preInit
/**
 * Returns an initiliazed instance of optionsChoice component.
 * @return the initialized component instance
 */
public ChoiceGroup getOptionsChoice () {
if (optionsChoice == null) {//GEN-END:|24-getter|0|24-preInit
            // write pre-init user code here
optionsChoice = new ChoiceGroup ("Options", Choice.MULTIPLE);//GEN-BEGIN:|24-getter|1|24-postInit
optionsChoice.append ("Filter unsafe", null);
optionsChoice.setFitPolicy (Choice.TEXT_WRAP_DEFAULT);
optionsChoice.setSelectedFlags (new boolean[] { false });
optionsChoice.setFont (0, null);//GEN-END:|24-getter|1|24-postInit
            // write post-init user code here
}//GEN-BEGIN:|24-getter|2|
return optionsChoice;
}
//</editor-fold>//GEN-END:|24-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: waitScreen ">//GEN-BEGIN:|26-getter|0|26-preInit
/**
 * Returns an initiliazed instance of waitScreen component.
 * @return the initialized component instance
 */
public WaitScreen getWaitScreen () {
if (waitScreen == null) {//GEN-END:|26-getter|0|26-preInit
            // write pre-init user code here
waitScreen = new WaitScreen (getDisplay ());//GEN-BEGIN:|26-getter|1|26-postInit
waitScreen.setTitle ("Searching...");
waitScreen.addCommand (getCancelSearch ());
waitScreen.setCommandListener (this);
waitScreen.setFullScreenMode (true);
waitScreen.setText ("Please wait while\nyour search is processed");
waitScreen.setTask (getTask ());//GEN-END:|26-getter|1|26-postInit
            // write post-init user code here
}//GEN-BEGIN:|26-getter|2|
return waitScreen;
}
//</editor-fold>//GEN-END:|26-getter|2|











//<editor-fold defaultstate="collapsed" desc=" Generated Getter: exitCommand ">//GEN-BEGIN:|18-getter|0|18-preInit
/**
 * Returns an initiliazed instance of exitCommand component.
 * @return the initialized component instance
 */
public Command getExitCommand () {
if (exitCommand == null) {//GEN-END:|18-getter|0|18-preInit
            // write pre-init user code here
exitCommand = new Command ("Exit", Command.EXIT, 0);//GEN-LINE:|18-getter|1|18-postInit
            // write post-init user code here
}//GEN-BEGIN:|18-getter|2|
return exitCommand;
}
//</editor-fold>//GEN-END:|18-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: searchCommand ">//GEN-BEGIN:|21-getter|0|21-preInit
/**
 * Returns an initiliazed instance of searchCommand component.
 * @return the initialized component instance
 */
public Command getSearchCommand () {
if (searchCommand == null) {//GEN-END:|21-getter|0|21-preInit
            // write pre-init user code here
searchCommand = new Command ("Search", Command.OK, 0);//GEN-LINE:|21-getter|1|21-postInit
            // write post-init user code here
}//GEN-BEGIN:|21-getter|2|
return searchCommand;
}
//</editor-fold>//GEN-END:|21-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: cancelSearch ">//GEN-BEGIN:|33-getter|0|33-preInit
/**
 * Returns an initiliazed instance of cancelSearch component.
 * @return the initialized component instance
 */
public Command getCancelSearch () {
if (cancelSearch == null) {//GEN-END:|33-getter|0|33-preInit
            // write pre-init user code here
cancelSearch = new Command ("Cancel", Command.CANCEL, 0);//GEN-LINE:|33-getter|1|33-postInit
            // write post-init user code here
}//GEN-BEGIN:|33-getter|2|
return cancelSearch;
}
//</editor-fold>//GEN-END:|33-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: viewCommand ">//GEN-BEGIN:|55-getter|0|55-preInit
/**
 * Returns an initiliazed instance of viewCommand component.
 * @return the initialized component instance
 */
public Command getViewCommand () {
if (viewCommand == null) {//GEN-END:|55-getter|0|55-preInit
            // write pre-init user code here
viewCommand = new Command ("View Image", Command.OK, 0);//GEN-LINE:|55-getter|1|55-postInit
            // write post-init user code here
}//GEN-BEGIN:|55-getter|2|
return viewCommand;
}
//</editor-fold>//GEN-END:|55-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: backCommand ">//GEN-BEGIN:|59-getter|0|59-preInit
/**
 * Returns an initiliazed instance of backCommand component.
 * @return the initialized component instance
 */
public Command getBackCommand () {
if (backCommand == null) {//GEN-END:|59-getter|0|59-preInit
            // write pre-init user code here
backCommand = new Command ("Back", Command.BACK, 0);//GEN-LINE:|59-getter|1|59-postInit
            // write post-init user code here
}//GEN-BEGIN:|59-getter|2|
return backCommand;
}
//</editor-fold>//GEN-END:|59-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: task ">//GEN-BEGIN:|31-getter|0|31-preInit
/**
 * Returns an initiliazed instance of task component.
 * @return the initialized component instance
 */
public SimpleCancellableTask getTask () {
if (task == null) {//GEN-END:|31-getter|0|31-preInit
            // write pre-init user code here
task = new SimpleCancellableTask ();//GEN-BEGIN:|31-getter|1|31-execute
task.setExecutable (new org.netbeans.microedition.util.Executable() {
public void execute () throws Exception {//GEN-END:|31-getter|1|31-execute
                    getWaitScreen().setText("Requesting page #"+String.valueOf(pageNumber));
                    HttpConnection hcon = null;
                    DataInputStream dis = null;
                    DataOutputStream dos = null;
                    //OutputStreamWriter dos = null;
                    StringBuffer message = new StringBuffer();
                    tag = tagField.getString().toLowerCase();
                    String requestBody = "";
                    if (pageNumber > 0)
                        requestBody += "page="+String.valueOf(pageNumber)+"&";
                    else
                        requestBody += "page=&";
                    requestBody += "tag="+tag;
                    try{
                        hcon = (HttpConnection)Connector.open("http://bayimg.com/ajax_tags.php", Connector.READ_WRITE);
                        hcon.setRequestMethod(HttpConnection.POST);
                        //hcon.setRequestProperty("Host", "bayimg.com");
                        hcon.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.0");
                        //hcon.setRequestProperty("Accept", "text/javascript, text/html, application/xml, text/xml, */*");
                        //hcon.setRequestProperty("Accept-Language", "en-us,en;q=0.5");
                        //hcon.setRequestProperty("Accept-Encoding", "none");
                        //hcon.setRequestProperty("Accept-Charset", "utf-8");
                        //hcon.setRequestProperty("Keep-Alive", "300");
                        //hcon.setRequestProperty("Connection", "keep-alive");
                        //hcon.setRequestProperty("X-Requested-With", "XMLHttpRequest");
                        //hcon.setRequestProperty("X-Prototype-Version", "1.5.1");
                        hcon.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
                        hcon.setRequestProperty("Referer", "http://bayimg.com/tag/"+tag);
                        byte[] data = requestBody.getBytes("UTF-8");
                        String cookie = "country=SE; images_per_page="+String.valueOf(imagesPerPage)+"; no_resize=0; ";
                        if (optionsChoice.isSelected(0)) {
                            cookie += "show_offensive=0";
                        }
                        else {
                            cookie += "show_offensive=1";
                        }
                        hcon.setRequestProperty("Cookie", cookie);
                        //hcon.setRequestProperty("Pragma", "no-cache");
                        //hcon.setRequestProperty("Cache-Control", "no-cache");
                        dos = hcon.openDataOutputStream();
                        //dos = new OutputStreamWriter(hcon.openOutputStream(), "UTF-8");
                        for (int i = 0; i < data.length; i++)
                            dos.writeByte(data[i]);
                        //dos.write(requestBody.getBytes());
                        hcon.setRequestProperty("Content-Length", String.valueOf(requestBody.length()));
                        //dos.flush();
                        dos.close();
                        int status = hcon.getResponseCode();
                        if (status != HttpConnection.HTTP_OK) {
                            throw new Exception("Not found: "+status);
                        }
                        dis = hcon.openDataInputStream();
                        int ch;
                        long len = hcon.getLength();
                        if (len != -1) {
                            for (int i = 0; i < len; i++) {
                                if ((ch = dis.read()) != -1) {
                                    message.append((char)ch);
                                }
                            }
                        }
                        else {
                            while ((ch = dis.read()) != -1) {
                                message.append((char)ch);
                            }
                        }
                        String output = //"<p align=\"center\"><a href=\"http://bayimg.com/caDmGaABD\"><img src=\"http://bayimg.com/thumb/cadmgaabd.jpg\" class=\"image-setting\" border=\"0\" alt=\"Image\"/></a><a href=\"http://bayimg.com/IAcDPAaba\"><img src=\"http://bayimg.com/thumb/iacdpaaba.jpg\" class=\"image-setting\" border=\"0\" alt=\"Image\"/></a><a href=\"http://bayimg.com/MabHHAaBP\"><img src=\"http://bayimg.com/thumb/mabhhaabp.jpg\" class=\"image-setting\" border=\"0\" alt=\"Image\"/></a><a href=\"http://bayimg.com/DabLKaabd\"><img src=\"http://bayimg.com/thumb/dablkaabd.jpg\" class=\"image-setting\" border=\"0\" alt=\"Image\"/></a><a href=\"http://bayimg.com/DabgcaAbd\"><img src=\"http://bayimg.com/thumb/dabgcaabd.jpg\" class=\"image-setting\" border=\"0\" alt=\"Image\"/></a><a href=\"http://bayimg.com/kabDaaaBd\"><img src=\"http://bayimg.com/thumb/kabdaaabd.jpg\" class=\"image-setting\" border=\"0\" alt=\"Image\"/></a><a href=\"http://bayimg.com/BAAPJAabm\"><img src=\"http://bayimg.com/thumb/baapjaabm.jpg\" class=\"image-setting\" border=\"0\" alt=\"Image\"/></a><a href=\"http://bayimg.com/HAADcaABd\"><img src=\"http://bayimg.com/thumb/haadcaabd.jpg\" class=\"image-setting\" border=\"0\" alt=\"Image\"/></a><a href=\"http://bayimg.com/HaADBAabd\"><img src=\"http://bayimg.com/thumb/haadbaabd.jpg\" class=\"image-setting\" border=\"0\" alt=\"Image\"/></a><a href=\"http://bayimg.com/HAAdAaAbd\"><img src=\"http://bayimg.com/thumb/haadaaabd.jpg\" class=\"image-setting\" border=\"0\" alt=\"Image\"/></a><a href=\"http://bayimg.com/PAaIKAaba\"><img src=\"http://bayimg.com/thumb/paaikaaba.jpg\" class=\"image-setting\" border=\"0\" alt=\"Image\"/></a><a href=\"http://bayimg.com/oAAioaAba\"><img src=\"http://bayimg.com/thumb/oaaioaaba.jpg\" class=\"image-setting\" border=\"0\" alt=\"Image\"/></a><a href=\"http://bayimg.com/oAaimaaBa\"><img src=\"http://bayimg.com/thumb/oaaimaaba.jpg\" class=\"image-setting\" border=\"0\" alt=\"Image\"/></a><a href=\"http://bayimg.com/OaAIlAaBA\"><img src=\"http://bayimg.com/thumb/oaailaaba.jpg\" class=\"image-setting\" border=\"0\" alt=\"Image\"/></a><a href=\"http://bayimg.com/fapdMAAaP\"><img src=\"http://bayimg.com/thumb/fapdmaaap.jpg\" class=\"image-setting\" border=\"0\" alt=\"Image\"/></a><a href=\"http://bayimg.com/LaPFMAaAH\"><img src=\"http://bayimg.com/thumb/lapfmaaah.jpg\" class=\"image-setting\" border=\"0\" alt=\"Image\"/></a><a href=\"http://bayimg.com/fapcoaaaf\"><img src=\"http://bayimg.com/thumb/fapcoaaaf.jpg\" class=\"image-setting\" border=\"0\" alt=\"Image\"/></a><a href=\"http://bayimg.com/fapCNAAaF\"><img src=\"http://bayimg.com/thumb/fapcnaaaf.jpg\" class=\"image-setting\" border=\"0\" alt=\"Image\"/></a><a href=\"http://bayimg.com/EaPCpaaaf\"><img src=\"http://bayimg.com/thumb/eapcpaaaf.jpg\" class=\"image-setting\" border=\"0\" alt=\"Image\"/></a><a href=\"http://bayimg.com/dapCGAAAf\"><img src=\"http://bayimg.com/thumb/dapcgaaaf.jpg\" class=\"image-setting\" border=\"0\" alt=\"Image\"/></a></p>";
                                message.toString();
                        getWaitScreen().setText("Parsing results...");
                        String imageUrl = "<a href=\"http://bayimg.com/";
                        int imageIndex = output.indexOf(imageUrl);
                        images = new Hashtable();
                        int i = 0;
                        while (imageIndex >= 0 && i < imagesPerPage) {
                            int endIndex = output.indexOf("\">", imageIndex+imageUrl.length());
                            if (endIndex > imageIndex) {
                                String imageCode = output.substring(imageIndex+imageUrl.length(), endIndex);
                                getWaitScreen().setText("Retrieving image "+imageCode);
                                Image img = null;
                                try {
                                    img = getImage("http://bayimg.com/thumb/"+imageCode.toLowerCase()+".jpg");
                                    images.put(imageCode, img);
                                }
                                catch (Exception ex) {}
                            }
                            imageIndex = output.indexOf(imageUrl, endIndex);
                            i++;
                        }
                        getImageList().Initialize(images, 75, 75, "Page "+String.valueOf(pageNumber));
                    }
                    catch (Exception ex) {
                        error = ex.getMessage();
                        throw ex;
                    }
                    finally {
                        if (dos != null) dos.close();
                        if (dis != null) dis.close();
                        if (hcon != null) hcon.close();
                    }
}//GEN-BEGIN:|31-getter|2|31-postInit
});//GEN-END:|31-getter|2|31-postInit
            // write post-init user code here
}//GEN-BEGIN:|31-getter|3|
return task;
}
//</editor-fold>//GEN-END:|31-getter|3|

//<editor-fold defaultstate="collapsed" desc=" Generated Method: viewImage ">//GEN-BEGIN:|75-entry|0|76-preAction
/**
 * Performs an action assigned to the viewImage entry-point.
 */
public void viewImage () {//GEN-END:|75-entry|0|76-preAction
 // write pre-action user code here
    String code = getImageList().getCurrent();
    String prevTitle = getImageList().getTitle();
    getImageList().setTitle("Retrieving image "+code);
    String url = "http://www.andresrovira.com/bi.php?code="+code+"&w=240&h=320";// "http://bayimg.com/image/"+code.toLowerCase()+".jpg";
    Image img = null;
    try {
        img = getImage(url);
    }
    catch (Exception ex) {
        error = ex.getMessage();
    }
    if (img != null) {
        getImageViewer().Initialize(img);
switchDisplayable (null, getImageViewer ());//GEN-LINE:|75-entry|1|76-postAction
 // write post-action user code here
    }
    else switchDisplayable(getAlert(), getImageList());
    getImageList().setTitle(prevTitle);
}//GEN-BEGIN:|75-entry|2|
//</editor-fold>//GEN-END:|75-entry|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: imageList ">//GEN-BEGIN:|67-getter|0|67-preInit
/**
 * Returns an initiliazed instance of imageList component.
 * @return the initialized component instance
 */
public ImageList getImageList () {
if (imageList == null) {//GEN-END:|67-getter|0|67-preInit
 // write pre-init user code here
imageList = new ImageList ();//GEN-BEGIN:|67-getter|1|67-postInit
imageList.setTitle ("Images");
imageList.addCommand (getBackCommand ());
imageList.addCommand (getExitCommand ());
imageList.addCommand (getViewCommand ());
imageList.addCommand (getNextCommand ());
imageList.addCommand (getPrevCommand ());
imageList.setCommandListener (this);//GEN-END:|67-getter|1|67-postInit
 // write post-init user code here
}//GEN-BEGIN:|67-getter|2|
return imageList;
}
//</editor-fold>//GEN-END:|67-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: imageViewer ">//GEN-BEGIN:|69-getter|0|69-preInit
/**
 * Returns an initiliazed instance of imageViewer component.
 * @return the initialized component instance
 */
public ImageViewer getImageViewer () {
if (imageViewer == null) {//GEN-END:|69-getter|0|69-preInit
 // write pre-init user code here
imageViewer = new ImageViewer ();//GEN-BEGIN:|69-getter|1|69-postInit
imageViewer.setTitle ("imageViewer");
imageViewer.addCommand (getBackCommand ());
imageViewer.setCommandListener (this);//GEN-END:|69-getter|1|69-postInit
 // write post-init user code here
}//GEN-BEGIN:|69-getter|2|
return imageViewer;
}
//</editor-fold>//GEN-END:|69-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: alert ">//GEN-BEGIN:|81-getter|0|81-preInit
/**
 * Returns an initiliazed instance of alert component.
 * @return the initialized component instance
 */
public Alert getAlert () {
if (alert == null) {//GEN-END:|81-getter|0|81-preInit
 // write pre-init user code here
alert = new Alert ("Error!", error, null, AlertType.ERROR);//GEN-BEGIN:|81-getter|1|81-postInit
alert.setTimeout (Alert.FOREVER);//GEN-END:|81-getter|1|81-postInit
 // write post-init user code here
}//GEN-BEGIN:|81-getter|2|
return alert;
}
//</editor-fold>//GEN-END:|81-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Method: goNextPage ">//GEN-BEGIN:|84-entry|0|85-preAction
/**
 * Performs an action assigned to the goNextPage entry-point.
 */
public void goNextPage () {//GEN-END:|84-entry|0|85-preAction
 // write pre-action user code here
    pageNumber++;
switchDisplayable (null, getWaitScreen ());//GEN-LINE:|84-entry|1|85-postAction
 // write post-action user code here
}//GEN-BEGIN:|84-entry|2|
//</editor-fold>//GEN-END:|84-entry|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Method: goPrevPage ">//GEN-BEGIN:|86-entry|0|87-preAction
/**
 * Performs an action assigned to the goPrevPage entry-point.
 */
public void goPrevPage () {//GEN-END:|86-entry|0|87-preAction
 // write pre-action user code here
    if (pageNumber > 0) {
        pageNumber--;
switchDisplayable (null, getWaitScreen ());//GEN-LINE:|86-entry|1|87-postAction
 // write post-action user code here
    }
}//GEN-BEGIN:|86-entry|2|
//</editor-fold>//GEN-END:|86-entry|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: nextCommand ">//GEN-BEGIN:|88-getter|0|88-preInit
/**
 * Returns an initiliazed instance of nextCommand component.
 * @return the initialized component instance
 */
public Command getNextCommand () {
if (nextCommand == null) {//GEN-END:|88-getter|0|88-preInit
 // write pre-init user code here
nextCommand = new Command ("Next Page", Command.ITEM, 0);//GEN-LINE:|88-getter|1|88-postInit
 // write post-init user code here
}//GEN-BEGIN:|88-getter|2|
return nextCommand;
}
//</editor-fold>//GEN-END:|88-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: prevCommand ">//GEN-BEGIN:|91-getter|0|91-preInit
/**
 * Returns an initiliazed instance of prevCommand component.
 * @return the initialized component instance
 */
public Command getPrevCommand () {
if (prevCommand == null) {//GEN-END:|91-getter|0|91-preInit
 // write pre-init user code here
prevCommand = new Command ("Prev", Command.ITEM, 0);//GEN-LINE:|91-getter|1|91-postInit
 // write post-init user code here
}//GEN-BEGIN:|91-getter|2|
return prevCommand;
}
//</editor-fold>//GEN-END:|91-getter|2|

    /**
     * Returns a display instance.
     * @return the display instance.
     */
    public Display getDisplay () {
        return Display.getDisplay(this);
    }

    /**
     * Exits MIDlet.
     */
    public void exitMIDlet() {
        switchDisplayable (null, null);
        destroyApp(true);
        notifyDestroyed();
    }

    /**
     * Called when MIDlet is started.
     * Checks whether the MIDlet have been already started and initialize/starts or resumes the MIDlet.
     */
    public void startApp() {
        if (midletPaused) {
            resumeMIDlet ();
        } else {
            initialize ();
            startMIDlet ();
        }
        midletPaused = false;
    }

    /**
     * Called when MIDlet is paused.
     */
    public void pauseApp() {
        midletPaused = true;
    }

    /**
     * Called to signal the MIDlet to terminate.
     * @param unconditional if true, then the MIDlet has to be unconditionally terminated and all resources has to be released.
     */
    public void destroyApp(boolean unconditional) {
    }
    
    private Image getImage(String url) throws Exception {
        HttpConnection hcon = null;
        DataInputStream dis = null;
        Image img = null;
        try {
            hcon = (HttpConnection)Connector.open(url);
            hcon.setRequestMethod(HttpConnection.GET);
            hcon.setRequestProperty("User-agent", "Profile/MIDP-2.0 Configuration/CLDC-1.0");
            hcon.setRequestProperty("Accept", "image/jpg");
            hcon.setRequestProperty("Connection", "close");
            hcon.setRequestProperty("Referer", "http://bayimg.com/tag/"+tag);
            int status = hcon.getResponseCode();
            if (status != HttpConnection.HTTP_OK) {
                throw new Exception("Not found: "+status);
            }
            int len = (int)hcon.getLength();
            if (len <= 0) {
                throw new Exception("Content-length <= 0 ("+String.valueOf(len)+")");
            }
            dis = hcon.openDataInputStream();
            byte[] imgData = new byte[len];
            dis.readFully(imgData);
            img = Image.createImage(imgData, 0, len);
        }
        catch (Exception ex) {
            error = ex.getMessage();
            throw ex;
        }
        finally {
            if (dis != null) dis.close();
            if (hcon != null) hcon.close();
        }
        return img;
    }

}
